import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../pigeon/generated.g.dart';
import '../utility/log.dart';
import '../../utility/calendar.dart' as calendar;

/// 应用使用统计测试页面
/// 用于测试获取和显示应用使用数据功能
class AppUsageStatsTest extends StatefulWidget {
  const AppUsageStatsTest({super.key});

  @override
  State<AppUsageStatsTest> createState() => _AppUsageStatsTestState();
}

class _AppUsageStatsTestState extends State<AppUsageStatsTest> {
  final _logBuffer = StringBuffer();
  late String _startDate;
  late String _endDate;
  final _startDateController = TextEditingController();
  final _endDateController = TextEditingController();
  final AppUsageStats _appUsageStats = AppUsageStats();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // 初始化日期为昨天和今天
    final today = DateTime.now();
    final yesterday = today.subtract(const Duration(days: 1));
    
    _startDate = calendar.dateTimeToInt(yesterday).toString();
    _endDate = calendar.dateTimeToInt(today).toString();
    
    _startDateController.text = _formatDate(yesterday);
    _endDateController.text = _formatDate(today);
    
    _appendLog('初始化日期范围: ${_formatDate(yesterday)} 到 ${_formatDate(today)}');
  }

  @override
  void dispose() {
    _startDateController.dispose();
    _endDateController.dispose();
    super.dispose();
  }

  /// 向日志缓冲区添加内容并更新UI
  void _appendLog(String log) {
    _logBuffer.write('\n$log');
    if (mounted) {
      setState(() {});
    }
  }

  /// 格式化日期为YYYY-MM-DD格式
  String _formatDate(DateTime date) {
    return DateFormat('yyyy-MM-dd').format(date);
  }

  /// 打开日期选择器选择开始日期
  Future<void> _selectStartDate() async {
    final date = await showDatePicker(
      context: context,
      initialDate: calendar.intToDateTime(int.parse(_startDate)),
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );
    
    if (date != null) {
      _startDate = calendar.dateTimeToInt(date).toString();
      _startDateController.text = _formatDate(date);
      _appendLog('选择开始日期: ${_formatDate(date)}');
    }
  }

  /// 打开日期选择器选择结束日期
  Future<void> _selectEndDate() async {
    final date = await showDatePicker(
      context: context,
      initialDate: calendar.intToDateTime(int.parse(_endDate)),
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );
    
    if (date != null) {
      _endDate = calendar.dateTimeToInt(date).toString();
      _endDateController.text = _formatDate(date);
      _appendLog('选择结束日期: ${_formatDate(date)}');
    }
  }

  /// 测试获取应用使用数据
  Future<void> _testFetchData() async {
    if (_isLoading) return;
    
    setState(() {
      _isLoading = true;
      _appendLog('开始获取数据...');
    });
    
    try {
      // 先进行认证
      await _appUsageStats.getAuthenticate();
      _appendLog('认证成功');
      
      // 获取数据
      final start = int.parse(_startDate);
      final end = int.parse(_endDate);
      
      _appendLog('请求数据: 类型=calorie, 开始=$start, 结束=$end');
      final results = await _appUsageStats.getData("calorie", start, end);
      
      if (results.isNotEmpty && results[0] != null) {
        final data = results[0]!;
        _appendLog('获取数据成功: ${data.value}');
      } else {
        _appendLog('未获取到数据');
      }
      
    } catch (e, stackTrace) {
      logger.e('获取数据失败', e, stackTrace);
      _appendLog('错误: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("应用使用统计测试"),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              // 权限设置按钮
              ElevatedButton(
                onPressed: () async {
                  try {
                    await _appUsageStats.getAuthenticate();
                    _appendLog('权限请求成功');
                  } catch (e) {
                    logger.e('权限请求失败', e);
                    _appendLog('权限请求失败: $e');
                  }
                },
                child: const Text("打开权限设置"),
              ),
              
              const SizedBox(height: 16.0),
              
              // 日期选择区域
              Card(
                elevation: 2.0,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      const Text(
                        "选择日期范围",
                        style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 12.0),
                      
                      // 开始日期选择
                      Row(
                        children: [
                          const Icon(Icons.calendar_today),
                          const SizedBox(width: 8.0),
                          Expanded(
                            child: TextField(
                              controller: _startDateController,
                              readOnly: true,
                              onTap: _selectStartDate,
                              decoration: const InputDecoration(
                                labelText: "开始日期",
                                suffixIcon: Icon(Icons.keyboard_arrow_down),
                              ),
                            ),
                          ),
                        ],
                      ),
                      
                      const SizedBox(height: 8.0),
                      
                      // 结束日期选择
                      Row(
                        children: [
                          const Icon(Icons.calendar_today),
                          const SizedBox(width: 8.0),
                          Expanded(
                            child: TextField(
                              controller: _endDateController,
                              readOnly: true,
                              onTap: _selectEndDate,
                              decoration: const InputDecoration(
                                labelText: "结束日期",
                                suffixIcon: Icon(Icons.keyboard_arrow_down),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              
              const SizedBox(height: 16.0),
              
              // 日志显示区域
              Card(
                elevation: 2.0,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      const Text(
                        "日志输出",
                        style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 8.0),
                      SizedBox(
                        height: 200.0,
                        child: SingleChildScrollView(
                          child: Text(
                            _logBuffer.isNotEmpty ? _logBuffer.toString() : "暂无日志...",
                            style: Theme.of(context).textTheme.bodyMedium,
                            softWrap: true,
                            overflow: TextOverflow.visible,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _testFetchData,
        tooltip: '获取数据',
        child: _isLoading 
            ? const CircularProgressIndicator(strokeWidth: 2.0) 
            : const Icon(Icons.refresh),
      ),
    );
  }
}